/**
 * @Title: index.js
 * @Description: index
 * @author: Fanchao
 * @date: 2020/12/14 11:46 上午
 * @version V1.0
 */
import React, { useEffect, useState } from "react";

import styles from "./index.less";
import SectionTitle from "components/SectionTitle";
import AddSomeButton from "components/AddSomeButton";
import { Button, Cascader, DatePicker, Form, Input, message, Modal, Popconfirm, Select, Table } from "antd";
import {
    createTeachClass,
    getTeachClassList,
    deleteTrainingType,
    getTrainingTypeList,
    getDepartmentTreeList,
    getRunTrainTaskInfoList
} from "api/index";
import moment from "moment";
import { getChildCascader } from "utils/index";

const { Option } = Select;

const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 }
};
const TeachClass = () => {
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [visible, setVisible] = useState(false);
    const [treeData, setTreeData] = useState([]);
    const [trainingTypeList, setTrainingTypeList] = useState([]);
    const [runTrainTaskInfoList, setRunTrainTaskInfoList] = useState([]);
    const [form] = Form.useForm();
    const fetch = async () => {
        setLoading(true);
        const result = await getTeachClassList();
        if (result.status === "success") {
            const dataSource = result.result;
            setDataSource(dataSource);
        } else {
            message.error(result.message);
        }
        setLoading(false);
    };
    const fetchTrainingTypeList = async () => {
        const result = await getTrainingTypeList();
        if (result.status === "success") {
            const trainingTypeList = result.result;
            setTrainingTypeList(trainingTypeList);
        } else {
            message.error(result.message);
        }
    };
    const getUnitsTreeData = async () => {
        const result = await getDepartmentTreeList();
        if (result.status === "success") {
            const data = result.result;
            const treeData = data.map(c => {
                if (!c.hasLowerDepartment) {
                    return {
                        value: c.departmentId,
                        label: c.departmentName
                    };
                } else {
                    return {
                        value: c.departmentId,
                        label: c.departmentName,
                        children: getChildCascader(c.lowerDepartmentModel)
                    };
                }
            });
            setTreeData(treeData);
        } else {
            message.error(result.message);
        }
    };
    const fetchRunTrainTaskInfoList = async (filter) => {
        const result = await getRunTrainTaskInfoList({ trainingTypeId: filter });
        if (result.status === "success") {
            const runTrainTaskInfoList = result.result;
            setRunTrainTaskInfoList(runTrainTaskInfoList);
        } else {
            message.error(result.message);
        }
    };
    useEffect(() => {
        fetch();
    }, []);
    const addItem = () => {
        getUnitsTreeData();
        fetchTrainingTypeList();
        setVisible(true);
    };
    const handleDelete = async ({ trainTypeId }) => {
        const result = await deleteTrainingType({ trainingTypeId: trainTypeId });
        if (result.status === "success") {
            message.success("删除成功");
            fetch();
        } else {
            message.error(result.message);
        }
    };
    const title = "新增教学班";
    const columns = [
        {
            title: "教学班名称",
            dataIndex: "classNo",
            align: "left"
        },
        {
            title: "培训类型",
            dataIndex: "trainingTypeName",
            align: "left"
        },
        {
            title: "入学时间",
            dataIndex: "enterSchoolDate",
            align: "left"
        },
        {
            title: "毕业时间",
            dataIndex: "leaveSchoolDate",
            align: "left"
        },
        {
            title: "操作",
            align: "left",

            render: (item) => {
                return (
                    <div>
                        <Popconfirm title="是否要删除？" onConfirm={() => handleDelete(item)}>
                            <Button style={{ padding: 2, color: "#C21217", fontWeight: "bold" }} type="link">删除</Button>
                        </Popconfirm>
                    </div>
                );
            }
        }
    ];
    return (
        <div className={styles.pageContainer}>
            <div className={styles.pageContainerHeader}>
                <SectionTitle title={title}/>
                <div style={{ width: "220px" }} onClick={() => addItem({})}>
                    <AddSomeButton title={title}/>
                </div>
            </div>
            <div className={styles.pageContainerTable}>
                <SectionTitle title={"已有教学班"}/>
                <div className={styles.tableContainer}>
                    <Table
                        bordered={false} // 是否有边框
                        rowKey='teachClassId' // 唯一key值
                        loading={loading} // 加载动画
                        columns={columns} // 表头
                        dataSource={dataSource}
                        pagination={false}
                    />
                </div>
            </div>
            <Modal
                title={title}
                visible={visible}
                // width="960px"
                onOk={() => {
                    form.validateFields().then(async values => {
                        values.enterSchoolDate = moment(values.enterSchoolDate).format("YYYY-MM-DD");
                        values.leaveSchoolDate = moment(values.leaveSchoolDate).format("YYYY-MM-DD");
                        values.leastDepartmentId = values.leastDepartmentId.pop();
                        const result = await createTeachClass(values);
                        if (result.status === "success") {
                            setVisible(false);
                            fetch();
                        } else {
                            message.error(result.message);
                        }
                    }).catch(info => {
                        // console.log(info);
                    });
                }}
                onCancel={() => {
                    form.resetFields();
                    setVisible(false);
                }}
            >
                <Form
                    {...layout}
                    layout="horizontal"
                    form={form}
                    name="basic"
                    // 表单默认值，只有初始化以及重置时生效 莫用
                    initialValues={{
                        // name: itemData.name
                    }}
                >
                    <Form.Item
                        label="培训类型"
                        name="trainingTypeId"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Select
                            placeholder="培训类型"
                            onChange={(e) => {
                                fetchRunTrainTaskInfoList(e);
                            }}
                        >
                            {
                                trainingTypeList.map(item => {
                                    return <Option key={item.trainTypeId}
                                                   value={item.trainTypeId}>{item.trainingTypeName}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="任务运行"
                        name="runTrainTaskId"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Select
                            placeholder="任务运行信息"
                        >
                            {
                                runTrainTaskInfoList.map(item => {
                                    return <Option key={item.runTrainTaskId}
                                                   value={item.runTrainTaskId}>{item.majorSysCode} {item.majorName} {item.startDate}至{item.endDate}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="教学班号"
                        name="classNo"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Input placeholder="请输入教学班号"/>
                    </Form.Item>
                    <Form.Item
                        label="所在单位"
                        name="leastDepartmentId"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Cascader
                            changeOnSelect
                            options={treeData}
                            placeholder="请选择所在单位"
                        />
                    </Form.Item>

                </Form>
            </Modal>
        </div>
    );
};

export default TeachClass;
